#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include<fcntl.h>

#include "gps.h"


gps_t open_gps(char *path)
{

	gps_t g;
	g.fd = open(path, O_RDONLY);

	printf("GPS ouvert\n");

	if(g.fd < 0)
	{	
		printf("Ouverture gps impossible\n");
		exit(0);
	}

	return g;
	
}


int read_gps(gps_t *g)
{
	int virgule = 0;
	int c_read = -1;
	char *pointer;
	int proceed = 1;
	char buff[MAXLINE];
	char drop[MAXLINE];
	
	while(proceed)
	{
		do
		{			
			c_read++;
			read(g->fd, g->data + c_read, 1);

			if(g->data[c_read] == ',')
			{
				if(virgule == 1)
				{
					g->data[c_read] = '#';
					g->data[++c_read] = ',';
				}
				virgule = 1;

			}
			else
				virgule = 0;
		

		}while(g->data[c_read] != '\n');

		g->data[c_read] = '\0';
		c_read = -1;


		if(strlen(g->data) < 10)
			continue;

		

		
		strcpy(buff, g->data);
		pointer = strtok(buff, ",");
		if( strcmp("$GPGGA", pointer) == 0)//14 champs gga
		{	
			strcpy(g->telemetry.time, strtok( NULL, ","));	
			strcpy(g->telemetry.latitude, strtok( NULL, ","));
			strcpy(g->telemetry.indicateur_latitude, strtok( NULL, ","));
			strcpy(g->telemetry.longitude, strtok( NULL, ","));
			strcpy(g->telemetry.indicateur_longitude, strtok( NULL, ","));

			
			strcpy(g->telemetry.fix, strtok( NULL, ","));	
			strcpy(g->telemetry.nb_sat, strtok( NULL, ","));	


			strcpy(drop, strtok( NULL, ","));
			strcpy(g->telemetry.altitude, strtok( NULL, ","));	

			proceed = 0;
		}

	}
	
	return 0;
}

void close_gps(gps_t *g)
{
    close(g->fd);
}
